import { ref } from "vue";

export function useGmap(el, opts, events) {
  const gmap = ref()
  const checkLoadStatus = (callback) => {
    function check() {
      !window.google ? window.requestAnimationFrame(check) : callback();
    }
    window.requestAnimationFrame(check);
  };

  const initMap = () => {
    return new Promise((resolve) => {
      if (window.google) {
        createMap();
        resolve();
      } else {
        checkLoadStatus(() => {
          createMap();
          resolve();
        });
      }
    });
  };

  const createMap = () => {
    gmap.value = new window.google.maps.Map(el, opts);
  }

  // 初始化地圖事件
  const initMapEvent = () => {
    for (const k in events) {
      const eventName = k
      gmap.value.addListener(eventName, events)
    }
  }

  return {
    gmap,
    initMap,
    initMapEvent
  }
}
